package com.lottery.controller;
import java.beans.PropertyEditor;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;

import com.lottery.entity.BaseRequest;
import com.lottery.entity.Result;
public class BaseController {
	private static final String DATE_FORMAT = "yyyy-MM-dd HH:mm:ss";

	protected static final String APPLICATION_JSON = "application/json;charset=UTF-8";

	protected static final String TEXT_HTML = "text/html;charset=UTF-8";

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;

	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		PropertyEditor editor = new CustomDateEditor(new SimpleDateFormat(DATE_FORMAT), true);
		binder.registerCustomEditor(Date.class, editor);
	}

	protected ModelAndView respMav(String viewName) {
		return new ModelAndView(viewName);
	}

	protected ModelAndView respMav(String viewName, Result result) {
		return new ModelAndView(viewName, "result", result);
	}

	protected ModelAndView respMav(String viewName, Result result, BaseRequest request) {
		ModelAndView mav = respMav(viewName, result);
		mav.addObject("request", request);
		mav.addObject("condition", request.buildCondition());

		return mav;
	}

	protected ResponseEntity<Result> respEntitySuccess(Result result) {
		return respEntity(result, HttpStatus.OK);
	}

	protected ResponseEntity<Result> respEntity(Result result, HttpStatus statusCode) {
		HttpHeaders headers = new HttpHeaders();
		headers.set("Content-Type", APPLICATION_JSON);
		return new ResponseEntity<Result>(result, headers, statusCode);
	}
	
	@ExceptionHandler({UnauthorizedException.class})
    public String authenticationException() {  
        return "unauthorizedPage";
    }

}
